package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.PermissionUtils;

import java.text.DecimalFormat;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityRulerBinding;
import stark.common.basic.utils.StkPermissionHelper;

public class RulerActivity extends BaseAc<ActivityRulerBinding> {

    public static boolean isRuler = false;
    private SensorManager mSensorManager;
    private float mDisDegree = 0f;
    private float mDegree = 0f;
    private float[] mAccelerometerValues = new float[3];
    private float[] mMagneticFieldValues = new float[3];
    private float mValues[] = new float[3];
    private float[] mInR = new float[9];
    private float[] mInclineMatrix = new float[9];
    private DecimalFormat mDecimalFormat = new DecimalFormat("#.#°");

    @Override
    protected int onCreate() {
        return R.layout.activity_ruler;
    }

    @Override
    protected void initView() {
        mDataBinding.ivRulerBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvRulerGetPermission.setOnClickListener(this);
        if (isRuler) {
            mDataBinding.tvRulerTitle.setText(getString(R.string.ruler_text));
            mDataBinding.rlRuler.setVisibility(View.VISIBLE);
            mDataBinding.rlProtractor.setVisibility(View.GONE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            mDataBinding.tvRulerTitle.setText(getString(R.string.protractor_text));
            mDataBinding.rlRuler.setVisibility(View.GONE);
            mDataBinding.rlProtractor.setVisibility(View.VISIBLE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.tvRulerGetPermission:
                getPermission();
                break;
        }
    }

    @Override
    protected void initData() {
        if (PermissionUtils.isGranted(Manifest.permission.CAMERA)) {
            initCamera();
            mDataBinding.tvRulerGetPermission.setVisibility(View.GONE);
        }
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA)
                .reqPermissionDesc(getString(R.string.get_camera_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        mDataBinding.tvRulerGetPermission.setVisibility(View.GONE);
                        initCamera();
                    }
                }).request();
    }

    private void initCamera() {
        mDataBinding.cameraView.setLifecycleOwner(this);
        mDataBinding.btnCalibrate.setOnClickListener(v -> {
            clickCalibrate();
        });
        mDataBinding.cameraView.setRequestPermissions(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerSensorListener();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterSensorListener();
    }

    private void registerSensorListener() {
        if (mSensorManager == null) {
            mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            // 加速传感器
            mSensorManager.registerListener(mSensorEventListener,
                    mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    Sensor.TYPE_ACCELEROMETER);
            // 磁力传感器
            mSensorManager.registerListener(mSensorEventListener,
                    mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
                    Sensor.TYPE_MAGNETIC_FIELD);
        }

    }

    private void unregisterSensorListener() {
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(mSensorEventListener);
            mSensorManager = null;
        }
    }

    private void clickCalibrate() {
        // 校准
        mDisDegree = mValues[1];
        mDataBinding.angleView.setAngle(0);
        mDataBinding.tvData.setText("0.0°");
    }

    private void calculateOrientation() {
        SensorManager.getRotationMatrix(mInR, mInclineMatrix, mAccelerometerValues, mMagneticFieldValues);
        SensorManager.getOrientation(mInR, mValues);
        mDegree = (float) Math.toDegrees(mValues[1] - mDisDegree);
        mDataBinding.angleView.setAngle(mDegree);
        mDegree = Math.abs(mDegree);
        float de = 90 - mDegree;
        mDataBinding.tvDegree.setText(mDecimalFormat.format(mDegree));
        mDataBinding.tvData.setText(mDecimalFormat.format(mDegree) + "\n" + mDecimalFormat.format(de));
    }

    private SensorEventListener mSensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            int type = event.sensor.getType();
            if (type == Sensor.TYPE_ACCELEROMETER) {
                mAccelerometerValues = event.values;
            } else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
                mMagneticFieldValues = event.values;
            }
            calculateOrientation();
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };

}